<template>
  <div class="upload-avatar">
    <a-upload
      :custom-request="handleUpload"
      :show-file-list="false"
      accept="image/*"
    >
      <template #upload-button>
        <div class="upload-wrapper">
          <div class="avatar-wrapper">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar-img" />
            <div v-else class="avatar-placeholder">
              <icon-plus />
              <div class="placeholder-text">上传头像</div>
            </div>
          </div>
        </div>
      </template>
    </a-upload>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Message } from '@arco-design/web-vue';
import { IconPlus } from '@arco-design/web-vue/es/icon';
import { OjUserService } from '@/api/gen-api/services/OjUserService';

const avatarUrl = ref('');

// 自定义上传方法
const handleUpload = async (option: any) => {
  const { file, onError, onSuccess } = option;

  // 检查文件类型和大小
  if (!file.type.startsWith('image/')) {
    Message.error('请上传图片文件');
    onError('文件类型错误');
    return;
  }

  if (file.size > 2 * 1024 * 1024) {
    // 2MB限制
    Message.error('图片大小不能超过2MB');
    onError('文件过大');
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', file);

    // 使用服务调用上传
    const response = await OjUserService.uploadAvatar(formData);

    if (response.result) {
      avatarUrl.value = response.result;
      onSuccess(response);
      Message.success('头像上传成功');
      // 触发更新事件
      emit('update');
    }
  } catch (error) {
    console.error('上传失败:', error);
    Message.error('头像上传失败');
    onError(error);
  }
};

// 定义emit
const emit = defineEmits(['update']);
</script>

<style scoped lang="less">
.upload-avatar {
  .upload-wrapper {
    cursor: pointer;
  }

  .avatar-wrapper {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    border: 2px dashed var(--color-border);
    transition: all 0.3s;

    &:hover {
      border-color: #2759cd;
    }

    .avatar-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .avatar-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: var(--color-text-3);

      .arco-icon {
        font-size: 24px;
        margin-bottom: 4px;
      }

      .placeholder-text {
        font-size: 12px;
      }
    }
  }
}
</style>
